<script setup lang="ts">
import {addressTypes, statusOpts} from "@/utils/status";
import {
  addAddress,
  deleteAddress,
  getAddressDetail,
  getAddressList,
  importAddress,
  updateAddress,
} from "@/api/louaddress";
import {AddressForm, AddressPageResult, AddressQuery,} from "@/api/louaddress/types";
import {addressFields} from "@/utils/field";
import {genFileId, UploadInstance} from "element-plus";

defineOptions({
  name: "Park",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const objFormRef = ref(ElForm);

const loading = ref(false);
const total = ref(0);
const lastPage = ref(0);

const route = useRoute?.();

const modelFields = addressFields();
const statusOptions = statusOpts();
const typeOpts = addressTypes();

const queryParams = reactive<AddressQuery>({
  pageNum: 1,
  pageSize: 100,
});

const lists = ref<AddressPageResult[]>();
const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<AddressForm>({
  status: 1,
  type: 0,
  pid: 0,
  sort: 40,
});

if (route.query?.pid) {
  queryParams.pid = route.query?.pid;
  queryParams.pageNum = 1;
  queryParams.keywords = undefined;
  formData.pid = route.query!.pid;
  handleQuery();
}

watch(
  () => route.query?.pid,
  (newVal) => {
    queryParams.pid = route.query?.pid;
    queryParams.pageNum = 1;
    queryParams.keywords = undefined;
    formData.pid = route.query!.pid;

    handleQuery();
  }
);

const rules = reactive({
  title: [{required: true, message: "请输入名称", trigger: "blur"}],
  status: [{required: true, message: "请选择状态", trigger: "blur"}],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getAddressList(queryParams)
    .then(({data}) => {
      lists.value = data.items || null;
      total.value = data.total;
      lastPage.value = data.lastPage || 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 打开表单弹窗 */
function openDialog(id?: number) {
  dialog.visible = true;

  if (id) {
    dialog.title = "修改地址";
    getAddressDetail(id).then(({data}) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增地址";
  }
}

/** 保存提交 */
function handleSubmit() {
  objFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        updateAddress(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addAddress(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  objFormRef.value.resetFields();
  objFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除 */
function handleDelete(id: number) {
  if (!id) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteAddress(id)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

// 导入数据地址  1 职工 2：就诊人员
const importData = reactive({
  type: 1,
  file: undefined,
  fileList: [],
});
const importVisible = ref(false);
const uploadRef = ref<UploadInstance>(); // 上传组件
const typeOptions = addressTypes();

/** Excel文件 Change */
function handleFileChange(file: any) {
  importData.file = file.raw;
}

/** Excel文件 Exceed  */
function handleFileExceed(files: any) {
  uploadRef.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
  importData.file = file;
}

/** 表单提交 */
const handleImport = useThrottleFn(() => {
  if (!importData?.file) {
    ElMessage.warning("上传Excel文件不能为空");
    return false;
  }

  loading.value = true;
  importAddress(importData?.type, importData?.file)
    .then((response) => {
      ElMessage.success(response.msg);
      handleQuery();
    })
    .finally(() => {
      importVisible.value = false;
      loading.value = false;
    });
});

function closeAddressDialog() {
  importVisible.value = false;
}

function openImportDialog() {
  importVisible.value = true;
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form class="pull-left" ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="">
          <el-input v-model="queryParams.keywords" placeholder="地址名称" clearable auto-complete="false"
                    @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="pull-right">
        <el-button
          v-hasPerm="['sys:address:edit']"
          type="success"
          @click="openDialog()"
        >
          <i-ep-plus/>
          新增
        </el-button>

        <el-button v-hasPerm="['sys:address:import']" type="primary" @click="openImportDialog()">
          <el-icon class="margin5-r">
            <UploadFilled/>
          </el-icon>
          导入
        </el-button>
      </div>
      <div class="clear"></div>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="lists"
        highlight-current-row
      >
        <el-table-column label="地址名称" prop="title" min-width="100">
          <template #default="scope">
            <el-link
              :href="'#/system/louaddress/?pid=' + scope.row.id"
              type="primary"
            >{{ scope.row.title }}
              <el-tag
                :type="scope.row.type == 1 ? 'danger' : 'success'"
                size="small"
                v-if="scope.row.type > 0"
              >
                {{ typeOpts[scope.row.type] }}
              </el-tag>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="排序 (越小越靠前)" prop="sort"/>
        <el-table-column label="状态" align="center" width="160">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'"
            >{{ statusOptions[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:address:edit']"
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            >
              <i-ep-edit class="margin3-r"/>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:address:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete class="margin3-r"/>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > queryParams.pageSize"
        v-model:total="total"
        v-model:lastPage="lastPage"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 编辑表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="540px"
      @close="closeDialog"
    >
      <el-form
        ref="objFormRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item
          :label="field.title"
          :prop="fk.toString()"
          v-for="(field, fk) in modelFields"
          :key="fk"
        >
          <el-radio-group v-model="formData[fk]" v-if="field.type == 'radio'">
            <el-radio :label="Number(ok)"  v-for="(op, ok) in field.options" :key="ok">{{ op }}</el-radio>
          </el-radio-group>

          <el-select v-model="formData[fk]" v-else-if="field.type == 'select'">
            <el-option
              :key="Number(op.id)"
              :label="op.title"
              v-for="op in field.options"
              :value="Number(op.id)"
            />
          </el-select>

          <el-input
            :type="field.type || 'text'"
            v-model="formData[fk]"
            :placeholder="'请输入' + field.title"
            v-else
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog" type="default">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="导入地址" v-model="importVisible" width="540px" @close="closeAddressDialog">
      <!-- 用户导入表单 -->
      <el-form :model="importData" label-width="140px">
        <el-form-item label="地址类型">
          <el-radio-group v-model="importData.type">
            <el-radio
              :label="Number(ok)"
              v-for="(op, ok) in typeOptions"
              :key="ok"
            >{{ op }}
            </el-radio>
          </el-radio-group>

        </el-form-item>
        <el-form-item label="Excel文件">
          <el-upload
            ref="uploadRef"
            action=""
            drag
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :limit="1"
            :auto-upload="false"
            :file-list="importData.fileList"
            :on-change="handleFileChange"
            :on-exceed="handleFileExceed"
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled/>
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div>xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleImport">确 定</el-button>
          <el-button @click="closeAddressDialog">取 消</el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>
